
use "$base_out/2016t1_FullyLinked_mainTE_own.dta", clear

keep $controls2 GradeName2016 gradename gradename2 d* academyid formerprovince2 stratascore percentscore_Z *T3ET15* *T1DG16*  treatment pupilid period Subject pupils tutors *tutor

drop if period<=1
drop if period=="T3ET15":periodl
drop if period=="T1DG16":periodl
compress
gen term1=(period=="T1MT16":periodl)
gen term2=(period=="T1ET16":periodl)
gen term3=(period=="T2MT16":periodl)
gen term4=(period=="T2ET16":periodl)
gen term5=(period=="T3MT16":periodl)
gen term6=(period=="T3ET16":periodl)
drop if term4==1
encode academyid, gen(academyid2)

foreach var in English_T3ET15_Z Swahili_T3ET15_Z math_T3ET15_Z lang_T1DG16_Z math_T1DG16_Z swa_T1DG16_Z{
egen terc_`var' = fastxtile(`var'), by(gradename2 period) nq(5)
}


foreach var in English_T3ET15_Z Swahili_T3ET15_Z math_T3ET15_Z lang_T1DG16_Z math_T1DG16_Z swa_T1DG16_Z{
egen tercwithin_`var' = fastxtile (`var'), by(academyid2 gradename2 period) nq(5)
}
drop period

rename terc_lang_T1DG16_Z terc_English_T1DG16_Z
rename terc_swa_T1DG16_Z  terc_Swahili_T1DG16_Z
rename tercwithin_lang_T1DG16_Z  tercwithin_English_T1DG16_Z
rename tercwithin_swa_T1DG16_Z tercwithin_Swahili_T1DG16_Z


 
capture drop Tercile
	gen Tercile=terc_math_T3ET15_Z
	replace Tercile=0 if Tercile==.
	fvset base 1 Tercile
    char Tercile[omit] 1
	label var Tercile "Tercile"

		
		
foreach time in  T3ET15{
foreach kind in terc {

eststo clear
foreach subject in math English {
    capture drop Tercile
	gen Tercile=`kind'_`subject'_`time'_Z
	replace Tercile=0 if Tercile==.
	fvset base 1 Tercile
    char Tercile[omit] 1
	label var Tercile "Tercile"
	
		eststo: reghdfe percentscore_Z c.treatment#i.Tercile i.Tercile $controls  if pupils==1 & Subject=="`subject'", vce(cluster academyid2) ab((gradename2#formerprovince2#stratascore)##c.(term*))
		estadd ysumm
		qui tab academyid if e(sample)==1 & treatment==0
		estadd scalar controls=r(r)
		estadd local ProvinceFE "Yes"
		estadd local Studentcontrols "Yes"
		estadd local Schoolscontrols "Yes"
		
		preserve
			parmest, norestore
			drop if strpos(parm,"treatment")==0
			drop in 1 
			mkmat estimate, matrix(B)
			keep p 
			mkmat p, matrix(A)
			forvalues i=1/5{
				local tempm=string(A[`i',1], "%9.2gc")
				file open newfile using "$results/LatexCode/`subject'_pvalue_quantile`i'.tex", write replace
				file write newfile "`tempm'"
				file close newfile
				
				local tempm=string(B[`i',1], "%9.2gc")
				file open newfile using "$results/LatexCode/`subject'_coef_quantile`i'.tex", write replace
				file write newfile "`tempm'"
				file close newfile

			}
		restore
		
		
		preserve
			parmest, norestore
			drop if strpos(parm,"treatment")==0
			keep in 1 
			mkmat estimate, matrix(B)
			keep p 
			mkmat p, matrix(A)
			local tempm=string(A[1,1], "%9.2gc")
			file open newfile using "$results/LatexCode/`subject'_pvalue_quantileNA.tex", write replace
			file write newfile "`tempm'"
			file close newfile
			
			local tempm=string(B[1,1], "%9.2gc")
			file open newfile using "$results/LatexCode/`subject'_coef_quantileNA.tex", write replace
			file write newfile "`tempm'"
			file close newfile
		restore
		
		
		
		
		
		preserve
		parmest, norestore
		drop if strpos(parm,"treatment")==0
		keep p 
		drop in 1 
		mkmat p, matrix(A)
		forvalues i=1/5{
			local tempm=string(A[`i',1], "%9.2gc")
			file open newfile using "$results/LatexCode/`subject'_pvalue_quintile`i'.tex", write replace
			file write newfile "`tempm'"
			file close newfile

		}
		restore
		
		
		test (_b[1.Tercile#c.treatment]= _b[3.Tercile#c.treatment]= _b[5.Tercile#c.treatment])
		local p_extreme=string(r(p), "%9.2gc")
		local tempm=string(`p_extreme', "%9.2gc")
		file open newfile using "$results/LatexCode/`subject'_p_extreme_quintile.tex", write replace
		file write newfile "`tempm'"
		file close newfile
		
		test (_b[1.Tercile#c.treatment]=_b[2.Tercile#c.treatment]= _b[3.Tercile#c.treatment]= _b[4.Tercile#c.treatment]= _b[5.Tercile#c.treatment])
		local p_all=string(r(p), "%9.2gc")
		local tempm=string(`p_all', "%9.2gc")
		file open newfile using "$results/LatexCode/`subject'_p_all_quintile.tex", write replace
		file write newfile "`tempm'"
		file close newfile
		
		
		coefplot, graphregion(color(white)) baselevels keep(*c.treatment*) ci ///
		rename(0.Tercile#c.treatment="NA" 1.Tercile#c.treatment="1" 2.Tercile#c.treatment="2" 3.Tercile#c.treatment="3" 4.Tercile#c.treatment="4" ///
		5.Tercile#c.treatment="5")  ///
		levels(95 90) ciopts(lwidth(medium thick)) ///
		vertical yline(0) xtitle("Quintile in `time'",size(medlarge)) ytitle("Math tutoring treatment effect",size(medlarge))  ///		
		note("p-value(H{sub:0}:Q{sub:1}=Q{sub:2}=Q{sub:3}=Q{sub:4}=Q{sub:5})= `p_all'" "p-value(H{sub:0}:Q{sub:1}=Q{sub:3}=Q{sub:5})= `p_extreme'",size(medlarge))
		
		graph export "$graphs/HeteroBaseline_`kind'_`subject'_`time'_withoutT2ET_quintile.pdf", replace
		
	forvalues i=1/5{
	  gen percentscore_Z`i'= percentscore_Z if Tercile==`i' 
	}
	rwolf percentscore_Z1 percentscore_Z2 percentscore_Z3  percentscore_Z4 percentscore_Z5  ///
	if pupils==1 & Subject=="`subject'", indepvar(treatment) method(reghdfe)	vce(cluster academyid2) ab((gradename2#formerprovince2#stratascore)#c.(term*))	///
	controls($control $controls_prescores ) seed(845894) reps(1000)
	forvalues i=1/5{
			local tempm=string(e(rw_percentscore_Z`i'), "%9.2gc")
			file open newfile using "$results/LatexCode/`subject'_rwolf_quintile`i'.tex", write replace
			file write newfile "`tempm'"
			file close newfile
	}
	drop percentscore_Z1 percentscore_Z2 percentscore_Z3  percentscore_Z4 percentscore_Z5
	drop Tercile
	}

				
	esttab  using "$results/LatexCode/het_all_pupils_`kind'_`time'_withoutT2ET_quintile.tex", se ar2 booktabs label b(a2) se(a2) nocon nonumber fragment ///
	star(* 0.10 ** 0.05 *** 0.01) ///
	replace keep(*#c.treatment ) stats(N N_clust controls , labels("N. of obs." "Number of schools" "Control schools")) ///
	nonotes addnotes("/specialcell{Clustered standard errors, by school, in parenthesis//  /sym{*} /(p<0.10/), /sym{**} /(p<0.05/), /sym{***} /(p<0.01/) }")
}
}
	
